<template>
  <div class="img2img-container">
    <el-row :gutter="20">
      <!-- 左侧生成面板 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8">
        <el-card class="generation-panel">
          <template #header>
            <div class="card-header">
              <span>图片生成图片</span>
              <div class="service-status">
                <el-tag v-if="serviceStatus" type="success" size="small">服务在线</el-tag>
                <el-tag v-else type="danger" size="small">服务离线</el-tag>
                <el-button :icon="Refresh" circle size="small" @click="checkService" :loading="checkingStatus"></el-button>
              </div>
            </div>
          </template>

          <el-form :model="generationForm" ref="generationFormRef" :rules="rules" label-position="top">
            <!-- 图片上传 -->
            <el-form-item label="上传图片" prop="initImage" class="upload-form-item">
              <div class="upload-container">
                <el-upload
                  class="image-uploader"
                  action="#"
                  :show-file-list="false"
                  :on-change="handleImageChange"
                  :auto-upload="false"
                  :limit="1"
                  accept=".jpg,.jpeg,.png"
                >
                  <template v-if="imageUrl">
                    <img :src="imageUrl" class="uploaded-image" />
                    <div class="image-overlay">
                      <el-button type="primary" size="small" circle>
                        <el-icon><Edit /></el-icon>
                      </el-button>
                    </div>
                  </template>
                  <div v-else class="upload-placeholder">
                    <el-icon :size="36"><Plus /></el-icon>
                    <div class="upload-text">点击上传图片</div>
                    <div class="upload-tips">
                      支持JPG、PNG格式，建议尺寸不超过1024x1024
                    </div>
                  </div>
                </el-upload>
              </div>
            </el-form-item>

            <!-- 模式选择 -->
            <el-form-item label="转换模式" prop="mode">
              <el-radio-group v-model="mode" @change="onModeChange">
                <el-radio label="anime">动漫风格</el-radio>
                <el-radio label="ghibli">吉卜力风格</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 提示词 -->
            <el-form-item label="提示词" prop="prompt">
              <el-input 
                v-model="generationForm.prompt" 
                type="textarea" 
                :rows="4" 
                placeholder="输入提示词描述你想要生成的图像"
              ></el-input>
            </el-form-item>

            <!-- 负面提示词 -->
            <el-form-item label="负面提示词">
              <el-input 
                v-model="generationForm.negativePrompt" 
                type="textarea" 
                :rows="2" 
                placeholder="描述你不希望在图像中出现的内容（可选）"
              ></el-input>
            </el-form-item>

            <!-- 高级选项 -->
            <el-collapse>
              <el-collapse-item title="高级选项">
                <el-form-item label="采样步数">
                  <el-slider 
                    v-model="generationForm.steps" 
                    :min="10" 
                    :max="150" 
                    :step="5" 
                    show-input
                  ></el-slider>
                </el-form-item>
                
                <el-form-item label="CFG缩放">
                  <el-slider 
                    v-model="generationForm.cfgScale" 
                    :min="1" 
                    :max="20" 
                    :step="0.5" 
                    show-input
                  ></el-slider>
                </el-form-item>
                
                <el-form-item label="降噪强度">
                  <el-slider 
                    v-model="generationForm.denoisingStrength" 
                    :min="0" 
                    :max="1" 
                    :step="0.05" 
                    show-input
                  ></el-slider>
                </el-form-item>
                
                <el-form-item label="种子值">
                  <el-input-number 
                    v-model="generationForm.seed" 
                    :min="-1" 
                    :max="2147483647" 
                    controls-position="right"
                    style="width: 100%"
                  ></el-input-number>
                  <div class="seed-options">
                    <el-button type="text" @click="generationForm.seed = -1">随机</el-button>
                    <el-button type="text" @click="generationForm.seed = Math.floor(Math.random() * 2147483647)">生成随机种子</el-button>
                  </div>
                </el-form-item>
              </el-collapse-item>
            </el-collapse>

            <!-- 提交按钮 -->
            <el-form-item>
              <el-button 
                type="primary" 
                @click="submitForm" 
                :loading="generating" 
                :disabled="!serviceStatus || !imageUrl"
                style="width: 100%"
              >
                生成图像
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧预览区域 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="16" :xl="16">
        <el-card class="preview-card">
          <template #header>
            <div class="card-header">
              <span>生成结果</span>
              <div v-if="generationResult">
                <el-tag :type="statusTypeMap[generationResult.status]">{{ statusTextMap[generationResult.status] }}</el-tag>
              </div>
            </div>
          </template>

          <div class="preview-container" v-loading="generating">
            <div v-if="generationResult && getImageUrl(generationResult)" class="image-container">
              <div class="image-comparison">
                <div class="original-image">
                  <h4>原始图像</h4>
                  <img :src="imageUrl" class="comparison-img" />
                </div>
                <div class="arrow">
                  <el-icon :size="30"><ArrowRight /></el-icon>
                </div>
                <div class="generated-image">
                  <h4>生成图像</h4>
                  <el-image 
                    :src="getAllImageUrls(generationResult)[selectedImageIndex]" 
                    fit="contain"
                    :preview-src-list="getAllImageUrls(generationResult)"
                    class="comparison-img result-image"
                  ></el-image>
                </div>
              </div>
              
              <!-- 缩略图选择区域 -->
              <div class="thumbnails-container" v-if="getAllImageUrls(generationResult).length > 1">
                <h4>所有生成图像</h4>
                <div class="thumbnails-grid">
                  <div 
                    v-for="(url, index) in getAllImageUrls(generationResult)" 
                    :key="index"
                    :class="['thumbnail-item', { active: selectedImageIndex === index }]"
                    @click="selectImage(index)"
                  >
                    <el-image 
                      :src="url" 
                      fit="cover"
                      class="thumbnail-image"
                    ></el-image>
                    <div class="thumbnail-label">{{ getThumbnailLabel(index) }}</div>
                  </div>
                </div>
              </div>
              
              <div class="image-info">
                <p>
                  <b>任务ID:</b> {{ generationResult.taskId }}
                </p>
                <p v-if="generationResult.modelName">
                  <b>模型:</b> {{ generationResult.modelName }}
                </p>
                <p v-if="generationResult.width && generationResult.height">
                  <b>尺寸:</b> {{ generationResult.width }}×{{ generationResult.height }}
                </p>
                <p v-if="generationResult.steps">
                  <b>步数:</b> {{ generationResult.steps }}
                </p>
                <p v-if="generationResult.cfgScale">
                  <b>CFG:</b> {{ generationResult.cfgScale }}
                </p>
                <p v-if="generationResult.denoisingStrength">
                  <b>降噪强度:</b> {{ generationResult.denoisingStrength }}
                </p>
                <p v-if="generationResult.samplerName">
                  <b>采样器:</b> {{ generationResult.samplerName }}
                </p>
                <p v-if="generationResult.seed !== undefined && generationResult.seed !== null">
                  <b>种子:</b> {{ generationResult.seed }}
                </p>
                <p v-if="generationResult.generationTime">
                  <b>生成耗时:</b> {{ (generationResult.generationTime / 1000).toFixed(2) }}秒
                </p>
                <p>
                  <b>创建时间:</b> {{ formatDateTime(generationResult.createTime) }}
                </p>
              </div>

              <div class="image-actions">
                <el-button type="primary" @click="downloadImage" :disabled="!getImageUrl(generationResult)">
                  <el-icon><Download /></el-icon> 下载图像
                </el-button>
                <el-button @click="regenerateWithSameParams">
                  <el-icon><RefreshRight /></el-icon> 重新生成
                </el-button>
              </div>
            </div>

            <div v-else-if="generating" class="placeholder">
              <p>正在生成图像，请稍候...</p>
            </div>
            
            <div v-else-if="generationResult && generationResult.status === 'failed'" class="error-container">
              <el-alert
                title="生成失败"
                type="error"
                description="图像生成失败，请检查参数后重试。"
                show-icon
              ></el-alert>
              <p v-if="generationResult.errorMessage" class="error-message">
                错误信息: {{ generationResult.errorMessage }}
              </p>
            </div>

            <div v-else class="placeholder">
              <div class="empty-image-large">
                <el-icon :size="48"><Picture /></el-icon>
                <p>暂无生成结果</p>
              </div>
              <p>上传图片并填写左侧表单后点击"生成图像"按钮开始生成</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 历史记录组件 -->
    <div class="full-width-section">
      <ModelConfigView @select-model="handleSelectModel" />
      <Img2ImgHistory 
        :generating="generating" 
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Refresh, 
  RefreshRight, 
  Download,
  Picture,
  Plus,
  ArrowRight,
  Edit
} from '@element-plus/icons-vue'
import { 
  generateAnimeStyle,
  generateGhibliStyle,
  checkServiceHealth,
  getTaskById,
  type Img2ImgRequest,
  type Img2ImgResponse,
  type ModelConfig
} from '@/api/img2img'
import { getImg2ImgModels } from '@/api/modelConfig'

// 导入子组件
import Img2ImgHistory from './Img2ImgHistory.vue'
import ModelConfigView from './ModelConfigView.vue'

// 服务状态
const serviceStatus = ref(false)
const checkingStatus = ref(false)

// 上传图片相关
const imageUrl = ref('')
const imageFile = ref<File | null>(null)

// 生成模式
const mode = ref('anime')

// 模型列表
const models = ref<ModelConfig[]>([])
const loadingModels = ref(false)

// 表单数据
const generationForm = reactive<Img2ImgRequest>({
  prompt: '',
  negativePrompt: '',
  initImage: '',
  steps: 30,
  cfgScale: 7,
  denoisingStrength: 0.75,
  seed: -1
})

// 表单验证规则
const rules = {
  prompt: [
    { required: true, message: '请输入提示词', trigger: 'blur' },
    { min: 3, message: '提示词至少需要3个字符', trigger: 'blur' }
  ],
  initImage: [
    { required: true, message: '请上传一张图片', trigger: 'change' }
  ]
}

// 状态管理
const generating = ref(false)
const generationFormRef = ref<any>(null)
const generationResult = ref<Img2ImgResponse | null>(null)
const selectedImageIndex = ref(0) // 当前选中的图片索引

// 状态映射
const statusTypeMap: Record<string, string> = {
  'pending': 'info',
  'processing': 'warning',
  'success': 'success',
  'failed': 'danger'
}

const statusTextMap: Record<string, string> = {
  'pending': '等待中',
  'processing': '处理中',
  'success': '成功',
  'failed': '失败'
}

// 检查服务状态
async function checkService() {
  checkingStatus.value = true
  try {
    const response = await checkServiceHealth()
    serviceStatus.value = response.code === 200 && Boolean(response.data)
    
    if (serviceStatus.value) {
      ElMessage.success('服务运行正常')
    } else {
      ElMessage.warning('服务未运行，请稍后重试')
    }
  } catch (error) {
    console.error('检查服务状态失败:', error)
    serviceStatus.value = false
    ElMessage.error('检查服务状态失败')
  } finally {
    checkingStatus.value = false
  }
}

// 处理图片变化
function handleImageChange(file: any) {
  if (!file || !file.raw) {
    ElMessage.error('上传失败，请重试')
    return
  }
  
  const rawFile = file.raw as File
  
  // 检查文件类型
  const isJPGOrPNG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
  if (!isJPGOrPNG) {
    ElMessage.error('只能上传JPG或PNG格式图片!')
    return
  }
  
  // 检查文件大小
  const isLt10M = rawFile.size / 1024 / 1024 < 10 // 限制大小为10MB
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过10MB!')
    return
  }
  
  // 读取图片并转换为Base64
  const reader = new FileReader()
  reader.onload = (e) => {
    if (e.target) {
      // 设置图片预览URL
      imageUrl.value = e.target.result as string
      // 提取Base64部分存入表单
      const base64Data = (e.target.result as string).split(',')[1]
      generationForm.initImage = base64Data
      
      // 显示成功消息
      ElMessage.success('图片上传成功')
      
      // 验证表单，移除可能的错误提示
      if (generationFormRef.value) {
        generationFormRef.value.validateField('initImage')
      }
    }
  }
  reader.onerror = () => {
    ElMessage.error('图片读取失败，请重试')
  }
  
  reader.readAsDataURL(rawFile)
  imageFile.value = rawFile
}

// 加载模型
async function loadModels() {
  loadingModels.value = true
  try {
    const response = await getImg2ImgModels()
    if (response.code === 200 && response.data) {
      // 类型转换以确保兼容性
      models.value = response.data as any as ModelConfig[]
      
      // 如果没有选择模式且有模型可用，使用默认模式
      if (!mode.value && models.value.length > 0) {
        // 查找模型名中包含anime的默认动漫模型
        const animeModel = models.value.find(model => 
          model.modelName === 'img2img_normal' || 
          model.modelName === 'anime_style'
        )
        if (animeModel) {
          mode.value = 'anime'
          // 设置表单中的提示词
          if (animeModel.positivePrompt) {
            generationForm.prompt = animeModel.positivePrompt
          }
          if (animeModel.negativePrompt) {
            generationForm.negativePrompt = animeModel.negativePrompt
          }
          // 设置步数和CFG
          generationForm.steps = animeModel.steps
          generationForm.cfgScale = animeModel.cfgScale
          generationForm.denoisingStrength = animeModel.denoisingStrength || 0.75
        }
      }
    }
  } catch (error) {
    console.error('加载模型配置失败:', error)
    ElMessage.error('加载模型配置失败')
    
    // 如果加载失败，使用默认值
    mode.value = 'anime'
  } finally {
    loadingModels.value = false
  }
}

// 模式变更处理
function onModeChange(newMode: string) {
  // 查找对应模式的模型
  let targetModel: ModelConfig | undefined
  
  if (newMode === 'anime') {
    targetModel = models.value.find(model => 
      model.modelName === 'img2img_normal' || 
      model.modelName === 'anime_style'
    )
  } else if (newMode === 'ghibli') {
    targetModel = models.value.find(model => 
      model.modelName === 'img2img_ghibli' || 
      model.modelName === 'ghibli_style'
    )
  }
  
  if (targetModel) {
    // 只更新模型相关参数，不填充提示词
    generationForm.steps = targetModel.steps
    generationForm.cfgScale = targetModel.cfgScale
    generationForm.denoisingStrength = targetModel.denoisingStrength || 0.75
  }
}

// 提交表单时设置正确的模型名
function getModelNameForMode(mode: string): string {
  if (mode === 'anime') {
    const animeModel = models.value.find(model => 
      model.modelName === 'img2img_normal' || 
      model.modelName === 'anime_style'
    )
    return animeModel?.modelName || 'anime_style'
  } else if (mode === 'ghibli') {
    const ghibliModel = models.value.find(model => 
      model.modelName === 'img2img_ghibli' || 
      model.modelName === 'ghibli_style'
    )
    return ghibliModel?.modelName || 'ghibli_style'
  }
  return 'anime_style' // 默认返回动漫风格
}

// 提交生成表单
function submitForm() {
  generationFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (!imageUrl.value) {
        ElMessage.warning('请先上传图片')
        return
      }
      
      // 设置模型名
      generationForm.modelName = getModelNameForMode(mode.value)
      
      generating.value = true
      try {
        let response
        if (mode.value === 'anime') {
          response = await generateAnimeStyle(generationForm)
        } else {
          response = await generateGhibliStyle(generationForm)
        }
        
        if (response.code === 200) {
          generationResult.value = response.data
          
          // 处理imageUrl
          if (!generationResult.value.imageUrl && generationResult.value.imageUrls) {
            const url = getImageUrlFromUrls(generationResult.value.imageUrls)
            if (url) {
              generationResult.value.imageUrl = url
            }
          }
          
          // 重置选中的图片索引
          selectedImageIndex.value = 0
          
          ElMessage.success('图像生成请求已提交')
          
          // 如果状态是pending或processing，开始轮询状态
          if (response.data.status === 'pending' || response.data.status === 'processing') {
            pollGenerationStatus(response.data.taskId)
          }
        } else {
          ElMessage.error(response.msg || '图像生成请求失败')
        }
      } catch (error) {
        console.error('图像生成错误:', error)
        ElMessage.error('图像生成请求失败')
      } finally {
        generating.value = false
      }
    }
  })
}

// 轮询生成状态
function pollGenerationStatus(taskId: string) {
  let attempts = 0
  const maxAttempts = 30 // 最多尝试30次，每次5秒
  
  const timer = setInterval(async () => {
    if (attempts >= maxAttempts) {
      clearInterval(timer)
      ElMessage.warning('生成任务超时，请在历史记录中查看结果')
      return
    }
    
    attempts++
    try {
      const response = await getTaskById(taskId)
      if (response.code === 200 && response.data) {
        const status = response.data.status
        
        // 处理imageUrl
        if (!response.data.imageUrl && response.data.imageUrls) {
          const url = getImageUrlFromUrls(response.data.imageUrls)
          if (url) {
            response.data.imageUrl = url
          }
        }
        
        // 更新当前结果
        generationResult.value = response.data
        
        // 如果已完成（成功或失败），停止轮询
        if (status === 'success' || status === 'failed') {
          clearInterval(timer)
          
          if (status === 'success') {
            // 重置选中的图片索引
            selectedImageIndex.value = 0
            ElMessage.success('图像生成成功')
          } else {
            ElMessage.error('图像生成失败: ' + (response.data.errorMessage || '未知错误'))
          }
        }
      } else {
        clearInterval(timer)
        ElMessage.error('获取生成状态失败')
      }
    } catch (error) {
      console.error('轮询状态错误:', error)
      clearInterval(timer)
    }
  }, 5000) // 每5秒检查一次
}

// 从imageUrls字符串中提取第一个URL
function getImageUrlFromUrls(imageUrls?: string | string[]): string | null {
  if (!imageUrls) return null
  
  // 如果imageUrls已经是数组，直接取第一个元素
  if (Array.isArray(imageUrls)) {
    return imageUrls.length > 0 ? imageUrls[0] : null
  }
  
  // 如果是字符串，尝试解析为JSON
  try {
    const urls = JSON.parse(imageUrls) as string[]
    return urls && urls.length > 0 ? urls[0] : null
  } catch (error) {
    console.error('解析图像URL错误:', error)
    return imageUrls || null // 如果无法解析，则返回原始字符串
  }
}

// 获取图像URL（支持两种格式）
function getImageUrl(record: Img2ImgResponse | null): string | null {
  if (!record) return null
  
  if (record.imageUrl) {
    return record.imageUrl
  }
  
  return getImageUrlFromUrls(record.imageUrls)
}

// 下载生成的图像
function downloadImage() {
  if (!generationResult.value) return
  
  const urls = getAllImageUrls(generationResult.value)
  if (urls.length === 0) return
  
  const imageUrl = urls[selectedImageIndex.value]
  if (!imageUrl) return
  
  // 从URL中提取文件名部分
  const fileName = imageUrl.split('/').pop() || `image_${generationResult.value.taskId}.png`
  
  const link = document.createElement('a')
  link.href = imageUrl
  link.download = fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 使用相同参数重新生成
function regenerateWithSameParams() {
  if (!generationResult.value || !imageUrl.value) return
  
  // 使用当前结果的参数更新表单
  generationForm.prompt = generationResult.value.prompt
  generationForm.negativePrompt = generationResult.value.negativePrompt || ''
  
  if (generationResult.value.steps) {
    generationForm.steps = generationResult.value.steps
  }
  
  if (generationResult.value.cfgScale) {
    generationForm.cfgScale = generationResult.value.cfgScale
  }
  
  if (generationResult.value.denoisingStrength) {
    generationForm.denoisingStrength = generationResult.value.denoisingStrength
  }
  
  // 生成新的随机种子或使用相同种子
  if (generationResult.value.seed !== undefined && generationResult.value.seed !== null) {
    generationForm.seed = generationResult.value.seed
  }
  
  // 提交表单
  submitForm()
}

// 格式化日期时间
function formatDateTime(timestamp: string | null) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}:${padZero(date.getSeconds())}`
}

function padZero(num: number) {
  return num.toString().padStart(2, '0')
}

// 选择模型处理
function handleSelectModel(model: any) {
  // 更新模式
  mode.value = model.mode || 'anime'
  
  // 只更新模型相关参数，不填充提示词
  generationForm.steps = model.steps || 30
  generationForm.cfgScale = model.cfgScale || 7
  generationForm.denoisingStrength = model.denoisingStrength || 0.75
  
  if (model.seed !== undefined && model.seed !== null) {
    generationForm.seed = model.seed
  } else {
    generationForm.seed = -1
  }
  
  ElMessage.success(`已选择模型: ${model.displayName}`)
}

// 获取所有图像URL（支持两种格式）
function getAllImageUrls(record: Img2ImgResponse | null): string[] {
  if (!record) return []
  
  // 如果imageUrls是数组，直接返回
  if (record.imageUrls && Array.isArray(record.imageUrls)) {
    return record.imageUrls
  }
  
  // 如果imageUrls是字符串，尝试解析
  if (record.imageUrls && typeof record.imageUrls === 'string') {
    try {
      return JSON.parse(record.imageUrls) as string[]
    } catch (error) {
      console.error('解析图像URL错误:', error)
      return record.imageUrl ? [record.imageUrl] : []
    }
  }
  
  // 如果只有单个imageUrl，则放入数组返回
  return record.imageUrl ? [record.imageUrl] : []
}

// 选择图片
function selectImage(index: number) {
  selectedImageIndex.value = index
}

// 获取缩略图标签
function getThumbnailLabel(index: number): string {
  // 根据图片名称特征判断类型
  const urls = getAllImageUrls(generationResult.value)
  if (!urls || !urls[index]) return `图片 ${index + 1}`
  
  const url = urls[index]
  if (url.includes('final_')) return '最终结果'
  if (url.includes('canny_')) return '轮廓图'
  if (url.includes('openpose_')) return '骨架图'
  if (url.includes('depth_')) return '深度图'
  if (url.includes('scribble_')) return '涂鸦图'
  
  return `图片 ${index + 1}`
}

// 生命周期钩子
onMounted(() => {
  checkService()
  loadModels()
})
</script>

<style scoped>
.img2img-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.service-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.generation-panel, .preview-card {
  margin-bottom: 20px;
}

.upload-form-item {
  width: 100%;
}

.upload-container {
  width: 100%;
  position: relative;
}

.image-uploader {
  width: 100%;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-uploader:hover {
  border-color: #409EFF;
}

.uploaded-image {
  width: 100%;
  height: auto;
  min-height: 300px;
  max-height: 450px;
  object-fit: contain;
  display: block;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  opacity: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: opacity 0.3s;
}

.image-uploader:hover .image-overlay {
  opacity: 1;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 300px;
  background-color: #fafafa;
  color: #8c939d;
  padding: 20px;
}

.upload-text {
  margin-top: 15px;
  font-size: 16px;
}

.upload-tips {
  margin-top: 15px;
  font-size: 12px;
  color: #909399;
  text-align: center;
  max-width: 80%;
}

.seed-options {
  margin-top: 8px;
  display: flex;
  gap: 10px;
}

.preview-container {
  min-height: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.image-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-comparison {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-bottom: 20px;
}

.original-image, .generated-image {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.original-image h4, .generated-image h4 {
  margin-bottom: 10px;
  font-weight: 500;
  color: #606266;
}

.comparison-img {
  max-width: 100%;
  max-height: 450px;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.arrow {
  margin: 0 20px;
  color: #909399;
}

.image-info {
  margin-top: 15px;
  width: 100%;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 10px;
}

.image-actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.placeholder {
  text-align: center;
  color: #909399;
}

.empty-image-large {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #909399;
}

.empty-image-large p {
  margin-top: 16px;
}

.error-container {
  width: 100%;
  max-width: 500px;
}

.error-message {
  margin-top: 15px;
  color: #F56C6C;
  white-space: pre-line;
}

.full-width-section {
  width: 100%;
}

.thumbnails-container {
  margin-top: 20px;
  width: 100%;
}

.thumbnails-container h4 {
  margin-bottom: 10px;
  font-weight: 500;
  color: #606266;
}

.thumbnails-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
}

.thumbnail-item {
  width: calc(33.33% - 10px);
  max-width: 150px;
  cursor: pointer;
  position: relative;
  border-radius: 4px;
  overflow: hidden;
  border: 2px solid transparent;
  transition: all 0.3s;
}

.thumbnail-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.thumbnail-item.active {
  border: 2px solid #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.thumbnail-image {
  width: 100%;
  height: 100px;
  object-fit: cover;
  display: block;
}

.thumbnail-label {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  padding: 4px;
  font-size: 12px;
  text-align: center;
  border-radius: 0 0 4px 4px;
}

@media (max-width: 768px) {
  .image-comparison {
    flex-direction: column;
    gap: 20px;
  }
  
  .arrow {
    transform: rotate(90deg);
    margin: 10px 0;
  }
  
  .image-info {
    grid-template-columns: 1fr;
  }
  
  .image-actions {
    flex-direction: column;
    width: 100%;
  }
  
  .comparison-img {
    max-height: 350px;
  }
}

.result-image {
  max-height: 450px;
  transition: transform 0.3s ease;
}

.result-image:hover {
  transform: scale(1.02);
}
</style> 